#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <cstring>

void Run(int port)
{
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "创建套接字失败" << std::endl;
        exit(1);
    }

    struct sockaddr_in host;
    host.sin_family = AF_INET;
    host.sin_port = htons(port);
    host.sin_addr.s_addr = htonl(INADDR_ANY);
    
    int n = ::bind(sockfd, (struct sockaddr*)&host, sizeof host);
    if(n < 0) {
        exit(1);
    }

    char recvbuf[1024];
    while(true) 
    {
        struct sockaddr_in client;
        socklen_t len = sizeof client;
        memset(recvbuf, 0, sizeof recvbuf);
        int n = recvfrom(sockfd, recvbuf, sizeof recvbuf, 0, (struct sockaddr*)&client, &len);
        if(n < 0) {
            std::cerr << "接收数据失败" << std::endl;
            exit(1);
        }

        std::cout << "接收到数据：" << recvbuf << std::endl;
        std::string sendbuf = "Echo: " + std::string(recvbuf);
        n = sendto(sockfd, sendbuf.c_str(), sendbuf.size(), 0, (struct sockaddr*)&client, len);
        if(n < 0) {
            std::cerr << "发送数据失败" << std::endl;
            exit(1);
        }

        std::cout << "发送数据：" << sendbuf << std::endl;
    }
}

int main(int argc, char* argv[])
{
    if(argc != 2) {
        std::cerr << "参数错误" << std::endl;
        std::cout << "Usage: " << argv[0] << " port" << std::endl;
        return -1;
    }

    int port = atoi(argv[1]);
    Run(port);

    return 0;
}